package com.dennytech.tac.utils.db;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import com.dennytech.tac.model.TravelGuide;

/**
 * TravelGuide local database
 * 
 * @deprecated from 2012.10.17, now load data from api
 *  
 * @author jun.deng
 *
 */
@Deprecated
public class TravelGuideDBHelper extends DBHelper<TravelGuide> {

	private static TravelGuideDBHelper instance;

	public static TravelGuideDBHelper instance() {
		return instance;
	}

	public static void init(Context c) {
		if (instance == null) {
			instance = new TravelGuideDBHelper(c);
		}
	}

	private TravelGuideDBHelper(Context c) {
		super(c, "tg");
	}

	@Override
	public List<TravelGuide> query() {
		List<TravelGuide> tgList = new ArrayList<TravelGuide>();
		try {
			String query = "SELECT * FROM " + tableName + " ORDER BY id;";
			Cursor c = db.rawQuery(query, null);
			if (c.moveToFirst()) {
				do {
					TravelGuide tg = new TravelGuide();
					tg.setId(c.getInt(0));
					tg.setName(c.getString(1));
					tg.setIntro(c.getString(2));
					tg.setDetail(c.getString(3));
					tg.setPhotoUrl(c.getString(4));
					tg.setTags(c.getString(5));
					tg.setTravel(c.getString(6));
					tgList.add(tg);

				} while (c.moveToNext());
				c.close();
			} else {
				c.close();
				return null;
			}
		} catch (Exception e) {
			return null;
		}
		return tgList;
	}

	public List<TravelGuide> query(String keyword) {
		List<TravelGuide> tgList = query();
		String trimKey = keyword.trim();

		if (TextUtils.isEmpty(trimKey)) {
			return tgList;
		}

		List<TravelGuide> result = new ArrayList<TravelGuide>();
		for (TravelGuide tg : tgList) {
			String[] tags = tg.getTags();
			if (tags != null) {
				for (int i = 0; i < tags.length; i++) {
					if (tags[i].contains(trimKey)) {
						result.add(tg);
						break;
					}
				}
				continue;
			}

			if (tg.getName() != null && tg.getName().contains(trimKey)) {
				result.add(tg);
				continue;
			}
		}

		return result;
	}

	@Override
	public String dbName() {
		return "tg.db";
	}

	@Override
	public File dbDir(Context c) {
		return c.getCacheDir();
	}

}
